#pragma once

/*
 * 登录处理类
 */
class LoginHandler : public JsonRequest<LoginHandler>
{
public:
	bool response()
	{
		std::string		user;
		std::string		pwd;
		sql_string<>	sql;
		const char*		ip			= getenv("REMOTE_ADDR");
		bool			allow		= false;
		std::string		uid;
		std::string		uuid;

		// 获取用户名和密码
		if(false == request::get("user", user)
				|| false == request::get("pwd", pwd))
		{
			err << "invalid parament";
			return false;
		}

		if(NULL == ip)
		{
			ip = "unknown";
		}

		// 验证用户名和密码
		sql.format("select id, uuid() from t_admin where name='%q' and passwd=password('%q')",
				user.c_str(), pwd.c_str());
		if( false == sql::signalQuery(sql.c_str(), &uid, &uuid, NULL) )
		{
			err << "use or password invalid";
			return false;
		}

		// 插入到session会语
		sql.format("insert into t_session(token,uid,user,ip,login, active)"
				" values('%q', %s, '%q', '%q', now(), now())",
				uuid.c_str(), uid.c_str(), user.c_str(), ip);
		if(false == sql::execute(sql.c_str()))
		{
			err << "save session failed";
			return false;
		}

		json.push_back(JSONNode("token", uuid.c_str()));
		return true;
	}

};

